<template>
  <div class="invite">
    <van-nav-bar
      title="邀请有礼"
      left-arrow
      @click-left="onClickLeft"
      fixed
      placeholder
      safe-area-inset-top
    />

    <div class="hero">
      <img class="hero-bg" :src="heroImg" alt="邀请有礼" />
      <div class="hero-text">
        <p class="t1">邀好友上购苗木，一起省钱更省心</p>
      </div>
    </div>

    <div class="content">
      <div class="card my-code">
        <div class="card-hd">
          <div class="title">
            <van-icon name="friends-o" />
            <span>我的邀请码</span>
          </div>
          <van-tag type="primary" plain>专属</van-tag>
        </div>
        <div class="code-box">
          <div class="code">{{ displayCode }}</div>
          <div class="actions">
            <van-button size="small" round type="primary" @click="handleCopy"
              >复制邀请码</van-button
            >
            <van-button size="small" round plain type="primary" @click="handleShare"
              >去分享</van-button
            >
          </div>
        </div>
        <div class="benefit">
          <van-notice-bar background="#F5FFF0" color="#2E7D32" :scrollable="false">
            邀请成功您与好友均可获得平台福利，数量有限先到先得
          </van-notice-bar>
        </div>
      </div>

      <div class="card bind-code">
        <div class="card-hd">
          <div class="title">
            <van-icon name="coupon-o" />
            <span>填写他人的邀请码</span>
          </div>
          <van-tag type="danger" plain>新人礼</van-tag>
        </div>
        <van-field
          v-model="inputCode"
          maxlength="12"
          clearable
          label="邀请码"
          placeholder="请输入好友的邀请码"
          :disabled="bindLocked"
        />
        <div class="tips" v-if="bindLocked">已绑定邀请码，无法再次修改</div>
        <van-button
          class="submit"
          :disabled="submitLoading || bindLocked"
          :loading="submitLoading"
          type="primary"
          round
          block
          @click="submitBind"
        >
          立即绑定
        </van-button>
        <ul class="why">
          <li>
            <img :src="icon1" alt="" />
            <div>
              <p class="p1">新人加速</p>
              <p class="p2">优先获取平台活动和运营扶持</p>
            </div>
          </li>
          <li>
            <img :src="icon2" alt="" />
            <div>
              <p class="p1">双向奖励</p>
              <p class="p2">邀请人与被邀请人均享专属奖励</p>
            </div>
          </li>
          <li>
            <img :src="icon3" alt="" />
            <div>
              <p class="p1">成长权益</p>
              <p class="p2">更多曝光与服务，助力生意增长</p>
            </div>
          </li>
        </ul>
      </div>

      <div class="card rules">
        <div class="card-hd">
          <div class="title">
            <van-icon name="notes-o" />
            <span>活动说明</span>
          </div>
        </div>
        <div class="rule-content">
          <p>1. 每位用户拥有一个唯一的邀请码，可在本页复制分享。</p>
          <p>2. 新用户首绑他人邀请码即可获得新人礼，老用户不可重复绑定。</p>
          <p>3. 成功邀请好友后，邀约双方均可获得奖励，具体以平台实际发放为准。</p>
          <p>4. 如遇异常，请联系平台客服处理。</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { showToast } from 'vant'
import bridge from '@/utils/bridge'
import { userInfo } from '@/api'
import { bindInvite, getInviteInfo } from '@/api'
// @ts-ignore
import heroImg from '@/assets/banner.png'
// @ts-ignore
import icon1 from '@/assets/icon1.png'
// @ts-ignore
import icon2 from '@/assets/icon2.png'
// @ts-ignore
import icon3 from '@/assets/icon3.png'

const myInviteCode = ref('')
const inputCode = ref('')
const bindLocked = ref(false)
const submitLoading = ref(false)

const displayCode = computed(() => (myInviteCode.value ? myInviteCode.value : '加载中...'))

const onClickLeft = () => {
  bridge.closeWebView()
}

const fetchCode = async () => {
  try {
    // 优先从专用接口获取邀请码信息（code: 0, data: string）
    if (getInviteInfo) {
      const { code, data } = await getInviteInfo()
      if ((code === 0 || code === 200) && typeof data === 'string' && data) {
        myInviteCode.value = data
        return
      }
    }
  } catch (e) {
    console.warn('getInviteInfo failed', e)
  }

  // 兜底：从用户信息读取
  try {
    const { code, data } = await userInfo()
    if ((code === 0 || code === 200) && data) {
      myInviteCode.value = data.inviteCode || data.invitationCode || ''
    }
  } catch (e) {
    console.warn('userInfo fallback failed', e)
  }
}

const handleCopy = async () => {
  if (!myInviteCode.value) {
    showToast('邀请码未加载')
    return
  }
  try {
    await navigator.clipboard.writeText(myInviteCode.value)
    showToast('已复制到剪贴板')
  } catch (e) {
    showToast('复制失败，请手动选择复制')
  }
}

const handleShare = () => {
  bridge.navigateBackTo({ value: 'shareInvite', inviteCode: myInviteCode.value })
}

const validate = () => {
  if (!inputCode.value) {
    showToast('请输入邀请码')
    return false
  }
  if (/\s/.test(inputCode.value)) {
    showToast('邀请码不能包含空格')
    return false
  }
  if (myInviteCode.value && inputCode.value === myInviteCode.value) {
    showToast('不能填写自己的邀请码')
    return false
  }
  return true
}

const submitBind = async () => {
  if (!validate()) return
  submitLoading.value = true
  try {
    const res: any = await (bindInvite as any)({ bindInviteCode: inputCode.value })
    const { code, msg, data } = res || {}
    if (code === 0 && data === true) {
      showToast('绑定成功，奖励将尽快发放')
      bindLocked.value = true
    } else {
      showToast(msg || '绑定失败，请稍后再试')
    }
  } catch (e: any) {
    const serverMsg = e?.msg || e?.message
    showToast(serverMsg || '网络异常，请稍后再试')
  } finally {
    submitLoading.value = false
  }
}

onMounted(async () => {
  bridge.setNavigationBarVisible({ value: '0' })
  await fetchCode()
})
</script>

<style lang="scss" scoped>
.invite {
  :deep(.van-nav-bar) {
    &::after {
      border: none;
    }
    .van-icon {
      color: #222;
    }
    .van-nav-bar__title {
      font-size: 17px;
      font-weight: normal;
      color: #222;
    }
  }

  :deep(.van-nav-bar__content) {
    height: 44px;
  }

  .hero {
    position: relative;
    .hero-bg {
      display: block;
      width: 100%;
    }
    .hero-text {
      position: static;
      padding: 8px 16px 0;
      .t1 {
        margin: 0 0 4px;
        font-size: 18px;
        color: #222222;
        font-weight: 600;
      }
      .t2 {
        margin: 0;
        font-size: 13px;
        color: #666666;
      }
    }
  }

  .content {
    padding: 12px;
  }

  .card {
    background: #ffffff;
    border-radius: 10px;
    padding: 14px;
    &:not(:last-child) {
      margin-bottom: 12px;
    }

    .card-hd {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;

      .title {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 15px;
        color: #222;
      }
    }
  }

  .my-code {
    .code-box {
      padding: 12px;
      background: linear-gradient(180deg, #f6fff1 0%, #ffffff 100%);
      border: 1px solid #eaf6e3;
      border-radius: 10px;

      .code {
        font-size: 28px;
        font-weight: 700;
        letter-spacing: 2px;
        text-align: center;
        color: #2e7d32;
        margin-bottom: 12px;
      }

      .actions {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
      }
    }

    .benefit {
      margin-top: 10px;
    }
  }

  .bind-code {
    .submit {
      margin-top: 12px;
    }
    .tips {
      margin-top: 6px;
      font-size: 12px;
      color: #999;
    }
    .why {
      list-style: none;
      padding: 0;
      margin: 14px 0 0;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 12px;
      li {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-align: center;
        padding: 14px 10px;
        background: linear-gradient(180deg, #ffffff 0%, #fafafa 100%);
        border: 1px solid #f2f3f5;
        border-radius: 10px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
        img {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background: #f5fff0;
          padding: 6px;
          margin-bottom: 8px;
        }
        .p1 {
          margin: 0 0 4px;
          font-size: 13px;
          color: #222;
          font-weight: 600;
        }
        .p2 {
          margin: 0;
          font-size: 12px;
          color: #888;
          line-height: 1.4;
        }
      }
    }
  }

  .rules {
    .rule-content {
      p {
        margin: 0 0 6px;
        font-size: 13px;
        color: #666;
      }
    }
  }
}
</style>
